import lejos.nxt.*;
/**
 * The locomotions of a  LEGO 9797 car is controlled by
 * sound detected through a microphone on port 1. 
 * 
 * @author  Ole Caprani
 * @version 23.08.07
 */
public class SoundCtrCar 
{
    private static int soundThreshold = 90;
    private static SoundSensor sound = new SoundSensor(SensorPort.S1);
    private static boolean stop = false;
    private static int[] buffer = new int[5];
    private static int i = 0;
    
    private static ButtonListener bl = new ButtonListener() {
		
		@Override
		public void buttonReleased(Button b) {
			LCD.clear();
			LCD.drawString("Program stopped", 0, 0);
			
		}
		
		@Override
		public void buttonPressed(Button b) {
			stop = true;
		}
	};
	
    private static  void waitForLoudSound() throws Exception
    {
        int soundLevel;
        
        
        Thread.sleep(500);
        do
        {
            soundLevel = sound.readValue();
            LCD.drawInt(soundLevel,4,10,0);
            buffer[i] = soundLevel;
            i = (i+1) % buffer.length;
            Thread.sleep(25);
        }
        while ( !isClapped() && !stop);
    }
    
    private static boolean isClapped() {
    	int j = (i-1) % buffer.length;  
    	int k = (i-2) % buffer.length;
    	j = j < 0 ? j + buffer.length : j;
    	k = k < 0 ? k + buffer.length : k;
    	
    	return buffer[j] < 50 && buffer[i] > 85 && buffer[j] > 10;
    }

    public static void main(String [] args) throws Exception
    {
        LCD.drawString("dB level: ",0,0);
        LCD.refresh();
        Button.ESCAPE.addButtonListener(bl);
        	   	   
        while (!stop)
        {
            waitForLoudSound();		    			   
            LCD.drawString("Forward ",0,1);
            Car.forward(100, 100);
		    
            waitForLoudSound();		    			   
            LCD.drawString("Right   ",0,1);
            Car.forward(100, 0);
		    
            waitForLoudSound();		    			   
            LCD.drawString("Left    ",0,1);
            Car.forward(0, 100);
		    
            waitForLoudSound();		    			   
            LCD.drawString("Stop    ",0,1); 
            Car.stop();
       }
       Car.stop();
       LCD.clear();
       LCD.drawString("Program stopped", 0, 0);
       Thread.sleep(2000); 
   }
}

